package com.bigflexlib.x.flash.display
{
	
	
	import flash.display.DisplayObject;
	import flash.display.DisplayObjectContainer;
	
	
	public class DisplayObjectContainerUtil
	{
		
		
		
		
		
		public static function syncChildrenToArray( parent:DisplayObjectContainer, childArr:Array ):void
		{
			
			var i:int, child:DisplayObject;
			

			for ( i=0; i<childArr.length; i++ )
			{
				child = childArr[i];
				if ( parent.contains( child ) )
				{
					if ( parent.getChildIndex( child ) != i )
						parent.setChildIndex( child, i );				
				}
				else
				{
					parent.addChildAt( child, i );				
				}
			}		
			
			
			var toRemove:Array = [ ];
			
			for ( ; i<parent.numChildren; i++ )
				toRemove.push( parent.getChildAt( i ) );
			
			
			for each ( child in toRemove )
				parent.removeChild( child );
		
		
		}
		
		
		
		
		
		
		/**
		 * 
		 * Recursively returns all descendants that can be accessed via the getChildAt() method
		 * ( you can also use this method on mx.core.Containers but it will return only UIComponents )
		 * 
		 * @param parent
		 * @param includeParent
		 * @param recurse
		 * @return 
		 * 
		 */		
		public static function getDescendants( parent:DisplayObjectContainer, includeParent:Boolean = false, recurse:Boolean = true ):Array
		{
			var result:Array = new Array();
			
			if ( includeParent )
				result.push( parent );
			
			for ( var i:int=0 ; i < parent.numChildren ; i++ )
			{
				var child:DisplayObject = parent.getChildAt( i );
				
				result.push( child );
				
				if ( child is DisplayObjectContainer && recurse )
					result.concat( getDescendants( child as DisplayObjectContainer, false ) );			
			}
			
			return result;
		
		}
		
		
		public static function removeAllChildren( parent:DisplayObjectContainer ):void
		{
			while ( parent.numChildren > 0 )
				parent.removeChildAt( 0 );		
		}
		
		
		
		public static function hideAllChildrenBut( parent:DisplayObjectContainer, child:DisplayObject ):void
		{
			for ( var i:int=0; i<parent.numChildren; i++ )
			{
				parent.getChildAt( i ).visible = ( parent.getChildAt( i ) == child );			
			}
		}
		
		
		
	}
	
}